import os
import glob
import cv2
import numpy as np
from PIL import Image

sli = 100  # 单次叠加一百张
start_index = 384  # 从文件夹内的第308张图片开始
result_path = "out/"
base_name = "startrails"
extension = ".jpg"
# 获取文件夹下已存在的文件名列表
existing_files = [filename for filename in os.listdir(result_path) if filename.startswith(base_name)]


# 放置原始图片的路径
base = 'G:\\MyFile\\sky\\721Lr'
names = sorted(os.listdir(base))
frame = None
amount = sli

for i in range(start_index, 1290):
    for count, name in enumerate(names):
        if count < i:  # 判断是否到达开始处理的图像位置索引
            continue
        elif count > (sli + i):  # 判断是否处理了”sli“张
            break
        else:
            if base_name == "startrails":
                base_name = os.path.splitext(name)[0].lower()
                print(base_name)
            if os.path.splitext(name)[1].lower() == '.jpg':
                percentage = (count - i) / amount * 100
                print(f'{percentage:.2f}%')
                path = os.path.join(base, name)
                print(path)
                curr = cv2.imread(path)
                if frame is None:
                    frame = curr
                else:
                    alpha = (count - i) / amount
                    curr = curr * (1 - alpha)
                    frame = np.maximum(frame, curr)

    # 计算新的文件名
    result_name = base_name + extension
    cv2.imwrite("out/" + result_name, frame)
    base_name = "startrails"
    frame = None  # 清空图像


# image_paths = []
# # 初始化叠加结果
# result = None
# im = None
#
# # for i in range(72, 120):
# #     filename = f'img/A{i:04d}.jpg'
# #     # img = cv2.imread(filename)
# #     image_paths.insert(0, filename)
#
# # 叠加处理
# for image_path in image_paths:
#     curr = cv2.imread(image_path)
#     if im is None:
#         im = curr
#     else:
#         im = np.maximum(im, curr)

# 调整亮度和对比度
# canvas = np.clip((frame * 1.1 + 10), 0, 255).astype(np.uint8)

# 显示结果
# cv2.namedWindow("startrails", 0)
# cv2.resizeWindow("startrails", 1200, 900)
# cv2.imshow("startrails", frame)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# cv2.imwrite("out/" + result_name, frame)
